package cn.skycity.framework.core.utils;

import cn.hutool.json.JSONUtil;
import cn.skycity.framework.core.model.Result;
import cn.skycity.framework.core.model.ResultCode;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.Writer;

/**
 * @ClassName ResponseUtils
 * @Decription TODO
 * @Author YingBo.Dai
 * @Date 2021/10/27
 * @Project cloud
 * 十月
 * 下午10:01 YingBo 2021
 **/
public class ResponseUtils {
    private ResponseUtils() {
        throw new IllegalStateException("Utility class");
    }
    /**
     * 通过流写到前端
     * @param response
     * @param obj
     */
    public static <T> void responseSucceed(HttpServletResponse response, T obj) throws IOException {
        Result<T> result = Result.success(obj);
        responseWrite(response, result);
    }

    /**
     * 通过流写到前端
     * @param response
     * @param msg
     * @throws IOException
     */
    public static void responseFailed(HttpServletResponse response, String msg) throws IOException {
        Result<?> result = Result.failed(msg);
        responseWrite(response, result);
    }

    private static void responseWrite(HttpServletResponse response, Result<?> result) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        try (
                Writer writer = response.getWriter()
        ) {
            writer.write(JSONUtil.toJsonStr(result));
            writer.flush();
        }
    }

    public static void writeErrorInfo(HttpServletResponse response, ResultCode resultCode) {
        switch (resultCode) {
            case ACCESS_UNAUTHORIZED:
            case TOKEN_INVALID_OR_EXPIRED:
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                break;
            case TOKEN_ACCESS_FORBIDDEN:
                response.setStatus(HttpStatus.FORBIDDEN.value());
                break;
            default:
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                break;
        }
        response.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        String body = JSONUtil.toJsonStr(Result.failed(resultCode));
        try {
            response.getWriter().write(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
